using System;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;

namespace Jerry.UiFrame
{
    public class JTextMesh : TextMeshProUGUI, IPointerClickHandler, IComponent
    {
        [SerializeField] [Tooltip("打字机效果")] private bool typewriter;

        [SerializeField] [Tooltip("打字机效果延迟时间")]
        private float delayTime;

        public Action<TMP_LinkInfo> OnLinkClick;

        private string _fullText;
        private List<TagInfo> _activeTags = new List<TagInfo>();
        private int visibleCount;

        public override string text
        {
            set
            {
                base.text = value;
                if (typewriter && gameObject.activeSelf)
                {
                    _fullText = value;
                    visibleCount = 0;
                    ParseTags();
                    StartCoroutine(TypeText());
                }
            }
            get => base.text;
        }

        public void OnPointerClick(PointerEventData eventData)
        {
            //<link="我是超链接"><u>网站 </u></link> 文本的内容如此
            int linkIndex =
                TMP_TextUtilities.FindIntersectingLink(this, eventData.position, UIConfig.UiCamera);

            if (linkIndex != -1)
            {
                TMP_LinkInfo linkInfo = textInfo.linkInfo[linkIndex];
                OnLinkClick?.Invoke(linkInfo);
                // Debug.Log(linkInfo.GetLinkText());//文本内容
                // Debug.Log(linkInfo.GetLinkID());//文本对应的链接
            }
        }

        public void SetVisible(bool bVisible)
        {
            gameObject.SetActive(bVisible);
        }
        
        public T GetChild<T>(string childName) where T : IComponent
        {
            var comp = transform.Find(childName).GetComponent<IComponent>();
            return (T)comp;
        }

        #region 打字机效果

        private void ParseTags()
        {
            _activeTags.Clear();
            bool inTag = false;
            string currentTag = "";
            int tagStartIndex = 0;

            for (int i = 0; i < _fullText.Length; i++)
            {
                if (_fullText[i] == '<')
                {
                    inTag = true;
                    tagStartIndex = i;
                    currentTag = "";
                }
                else if (_fullText[i] == '>')
                {
                    inTag = false;
                    bool isSpriteTag = currentTag.StartsWith("sprite"); // 新增
                    _activeTags.Add(new TagInfo
                    {
                        StartIndex = tagStartIndex,
                        Tag = currentTag,
                        IsClosing = currentTag.StartsWith("/"),
                        IsSprite = isSpriteTag // 新增字段
                    });
                }
                else if (inTag)
                {
                    currentTag += _fullText[i];
                }
            }
        }

        private System.Collections.IEnumerator TypeText()
        {
            Stack<string> openTags = new Stack<string>();
            int currentIndex = 0;
            base.text = "";

            while (currentIndex < _fullText.Length)
            {
                if (_fullText[currentIndex] == '<')
                {
                    // 处理标签
                    var tag = _activeTags.Find(t => t.StartIndex == currentIndex);
                    if (tag != null)
                    {
                        // 处理sprite标签的特殊情况
                        if (tag.IsSprite)
                        {
                            // 直接插入完整sprite标签
                            base.text = _fullText.Substring(0, tag.StartIndex + tag.Tag.Length + 2); 
                            currentIndex = tag.StartIndex + tag.Tag.Length + 2; // 跳过整个标签
                            yield return new WaitForSeconds(delayTime);
                            continue;
                        }
                        
                        if (tag.IsClosing)
                        {
                            if (openTags.Count > 0)
                                openTags.Pop();
                        }
                        else
                        {
                            openTags.Push(tag.Tag);
                        }

                        currentIndex = tag.StartIndex + tag.Tag.Length + 2; // < + tag + >
                    }
                }
                else
                {
                    // 构建可见文本
                    string visibleText = _fullText.Substring(0, currentIndex + 1);
                    visibleText += "</color>"; // 临时关闭颜色标签（如果有）

                    // 添加未闭合标签
                    foreach (string tag in openTags)
                    {
                        visibleText += $"<{tag}>";
                    }

                    base.text = visibleText;
                    currentIndex++;
                    yield return new WaitForSeconds(delayTime);
                }
            }
        }

        private class TagInfo
        {
            public int StartIndex;
            public string Tag;
            public bool IsClosing;
            public bool IsSprite; // 新增标识
        }

        #endregion
    }
}